#include "GamePlayState.h"

GamePlayState::GamePlayState(BeanieCore* a_core, bool a_renew)
{
	m_core = a_core;

	m_name = "GamePlayState";
	m_selfId = GAMEPLAY;
	m_swapId = GAMEPLAY;
	m_completed = false;
	m_renew = a_renew;
	complete = false;
}

void GamePlayState::init()
{
	m_world.init(CELL_COL,CELL_ROW);
	m_map.init(m_core,&m_world);
	//m_map.changeLevel(2);
	object = m_map.objectiveLoc();
	escape = m_map.escapeLoc();
	m_player = m_map.currentPlayer();
}

void GamePlayState::release()
{
	m_map.release();
	m_world.destroy();
}

void GamePlayState::input()
{
	m_player->input();

	if(m_core->keyPress(KEY_ESCAPE))
	{
		m_swapId = GAMEMENU;
		m_completed = true;
		m_map.setAlerted(false);
		m_map.changeLevel(m_map.getLevel());
	}
}

void GamePlayState::update()
{
	float time = m_core->getElapsed();

	m_world.updatePhysics(time);
	m_world.generateContacts(time);
	m_world.resolveContacts(time);

	m_core->updateCamera(m_player->getPos());

	V2DF min, max;
	m_core->getCam(&min,&max);
	m_world.cullBox(min,max);

	m_map.update();

	m_player->update();

	if (!complete)
	{
		if(satCollision(object->m_body->m_vertR,object->m_body->m_vertRN, 4,
			m_player->m_body->m_vertR,m_player->m_body->m_vertRN,4))
			complete = true;
	}
	else
	{
		if(satCollision(escape->m_body->m_vertR,escape->m_body->m_vertRN, 4,
			m_player->m_body->m_vertR,m_player->m_body->m_vertRN,4))
		{
			int map;
			map = m_map.nextLevel();
			m_player = m_map.currentPlayer();
			object = m_map.objectiveLoc();
			escape = m_map.escapeLoc();
			complete = false;
		}
	}
	if(m_core->keyPress(DIK_PGUP))
	{
		int map;
		map = m_map.nextLevel();
		m_player = m_map.currentPlayer();
		object = m_map.objectiveLoc();
		escape = m_map.escapeLoc();
		complete = false;
	}
}

void GamePlayState::draw()
{
	m_map.render();

	m_player->draw();

	if(!complete)
	{
		object->draw();
		drawRect(m_core,
			object->m_body->m_vertR,
			CL_BLUE);
	}
	else
	{
		escape->draw();
		drawRect(m_core,
			escape->m_body->m_vertR,
			CL_MAGENTA);
	}
}

void GamePlayState::preLoop()
{

}

void GamePlayState::postLoop()
{
	if(m_map.alerted())
	{
		m_swapId=GAMELOSE;
		m_completed=true;
		m_map.setAlerted(false);
		m_map.changeLevel(m_map.getLevel());
	}
}